<template>
  <div class="container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6" v-for="(item, index) in statisticsData" :key="index">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <div class="statistics-item">
            <div class="icon-wrapper" :style="{ background: item.bgColor }">
              <el-icon><component :is="item.icon" /></el-icon>
            </div>
            <div class="content">
              <div class="title">{{ item.title }}</div>
              <div class="value">{{ item.value }}</div>
              <div class="trend">{{ item.trend >= 0 ? '+' : '' }}{{ item.trend }}% 较上周</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="16">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>近7天销售趋势</span>
            </div>
          </template>
          <div ref="salesChartRef" style="height: 350px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div ref="orderChartRef" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 库存预警 -->
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>库存预警</span>
          <el-button type="primary" size="small">查看全部</el-button>
        </div>
      </template>
      <el-table :data="lowStockList" style="width: 100%">
        <el-table-column prop="id" label="商品ID" width="180" />
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="inventory" label="库存数量" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { Money, ShoppingCart, User, Goods } from '@element-plus/icons-vue'
import { getLowStockListAPI, getStatisticsDataAPI, getStatisticsOrderDataAPI } from '@/apis/admin'

const statisticsData = ref([])
const orderObject = ref([])
//获取数据卡片数据
const getStatisticsData = async () => {
  const res = await getStatisticsDataAPI()
  if (res.code === 0) {
    const { totalSales, orderCount, userCount, goodsCount } = res.data
    statisticsData.value = [
      {
        title: '总销售额',
        value: `¥${totalSales}`,
        trend: 12.5,
        icon: Money,
        bgColor: '#409EFF'
      },
      {
        title: '订单总量',
        value: orderCount,
        trend: 8.2,
        icon: ShoppingCart,
        bgColor: '#67C23A'
      },
      {
        title: '用户数量',
        value: userCount,
        trend: 6.8,
        icon: User,
        bgColor: '#E6A23C'
      },
      {
        title: '商品总数',
        value: goodsCount,
        trend: -2.5,
        icon: Goods,
        bgColor: '#F56C6C'
      }
    ]
  }
  const orderData = await getStatisticsOrderDataAPI()
  if (orderData.code === 0) {
    orderObject.value = orderData.data
    // 在这里获取到数据后初始化饼图
    initOrderChart()
  }
}

// const statisticsData = ref([
//   {
//     title: '总销售额',
//     value: '¥126,560',
//     trend: 12.5,
//     icon: Money,
//     bgColor: '#409EFF'
//   },
//   {
//     title: '订单总量',
//     value: '1,280',
//     trend: 8.2,
//     icon: ShoppingCart,
//     bgColor: '#67C23A'
//   },
//   {
//     title: '用户数量',
//     value: '3,120',
//     trend: 6.8,
//     icon: User,
//     bgColor: '#E6A23C'
//   },
//   {
//     title: '商品总数',
//     value: '580',
//     trend: -2.5,
//     icon: Goods,
//     bgColor: '#F56C6C'
//   }
// ])

// 图表实例
const salesChartRef = ref(null)
const orderChartRef = ref(null)
let salesChart = null
let orderChart = null

// 在 setup 中
const lowStockList = ref([])

const getLowStockData = async () => {
  try {
    const res = await getLowStockListAPI()
    if (res.code === 0) {
      lowStockList.value = res.data
    }
  } catch (error) {
    console.error('获取低库存商品失败:', error)
  }
}

// 获取近7天的日期
const getLast7Days = () => {
  const dates = []
  const sales = []
  for (let i = 6; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }))
    // 这里的销售数据应该从后端获取，暂时用随机数模拟
    sales.push(Math.floor(Math.random() * 2000 + 1000))
  }
  return { dates, sales }
}

// 初始化销售趋势图表
const initSalesChart = () => {
  if (!salesChartRef.value) return

  salesChart = echarts.init(salesChartRef.value)
  const { dates, sales } = getLast7Days()

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      name: '销售额',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        data: sales,
        smooth: true,
        itemStyle: {
          color: '#fd715d'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#fd715d' },
              { offset: 1, color: 'rgba(253, 113, 93, 0.1)' }
            ]
          }
        }
      }
    ]
  }

  salesChart.setOption(option)
}

// 初始化订单状态分布图表
const initOrderChart = () => {
  orderChart = echarts.init(orderChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    // 图例配置
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: '50%',

        data: [
          { value: orderObject.value.noPayTotal, name: '待付款' },
          { value: orderObject.value.noSendTotal, name: '待发货' },
          { value: orderObject.value.sendTotal, name: '已发货' },
          { value: orderObject.value.finishTotal, name: '已完成' },
          { value: orderObject.value.cancelTotal, name: '已取消' }
        ],
        // 高亮样式配置
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  // 将定义好的配置项（option）应用到图表实例上
  orderChart.setOption(option)
}

onMounted(() => {
  initSalesChart()
  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    salesChart?.resize()
    orderChart?.resize()
  })

  getLowStockData()
  getStatisticsData()
})
</script>

<style scoped>
.container {
  padding: 20px;
}

.statistics-item {
  display: flex;
  align-items: center;
}

.icon-wrapper {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.icon-wrapper :deep(.el-icon) {
  font-size: 24px;
  color: #fff;
}

.content {
  flex: 1;
}

.title {
  font-size: 14px;
  color: #909399;
}

.value {
  font-size: 24px;
  font-weight: bold;
  margin: 8px 0;
}

.trend {
  font-size: 12px;
  color: #67c23a;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>
